package com.example.springbootlocal.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.springbootlocal.system.domain.Log;
import com.example.springbootlocal.system.service.LogService;
import com.example.springbootlocal.utils.Requestutils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletRequest;


/**
 * @author X.I.O
 * @title: LogFilter
 * @projectName spring-boot-local
 * @description: TODO
 * @date 2021/11/11 15:42
 */
@Order(3)
@Slf4j
@ControllerAdvice
@Configuration
public class LogFilter implements ResponseBodyAdvice<Object> {

    @Autowired
    private LogService sysLogService;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HttpServletRequest req = Requestutils.getHttpServletRequest();
        ApiOperation api=returnType.getMethodAnnotation(ApiOperation.class);
        String apiName="未定义接口名";
        if(api!=null){
            apiName=api.value();
        }
        String urlClazz = req.getContextPath();
        String url=req.getRequestURI();
        // 获取请求参数内容json字符串
        String paramData = JSON.toJSONString(req.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue);
        //获取请求方法
        String metnod=req.getMethod();
        String ip=req.getRemoteHost();
        Log log=new Log();
        log.setLogName(apiName);
        log.setClazz(urlClazz);
        log.setParams(paramData);
        log.setUrl(url);
        sysLogService.saveLog(log);
        return body;
    }
}
